<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" :width="600" @ok="handleSubmit">
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" name="DictDataDrawer" setup>
import {ref, computed} from 'vue';
import {BasicForm, useForm} from '@/components/form/index';
import {BasicDrawer, useDrawerInner} from '@/components/drawer';
import {Api} from '../data/dict.data.api';
import {dictDataFormSchema} from '../data/data';
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);
//计算标题
const getTitle = computed(() => (!isUpdate.value ? '新增字典项' : '编辑字典项'));
//配置表单
const [registerForm, {resetFields, setFieldsValue, updateSchema, validate, formSubmit}] = useForm({
  rowKey: 'dictDataId',
  saveApi: Api.add,
  updateApi: Api.update,
  schemas: dictDataFormSchema,
});
//表单赋值
const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
  setDrawerProps({confirmLoading: false});
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (isUpdate.value) {
    await setFieldsValue(data.record);
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    setDrawerProps({confirmLoading: true});
    await formSubmit({
      emit
    });
    closeDrawer();
  } finally {
    setDrawerProps({confirmLoading: false});
  }
}
</script>
